import React, { useCallback, useEffect, useState } from 'react'

import Carthead from './cart_head/index.js'
import Cartfoo from './cart_foo/index.js'
import Maylike from './maylike/index.js';
import "./index.scss"
import { perOrder } from '../../api/perOrder.js'
import { useNavigate } from 'react-router-dom';
import { getYOULieklistAction } from '../../store/actions/rydata.js'
import { connect } from 'react-redux';
import { editCartAction } from '../../store/actions/cart.js'
const Cart = (props) => {
  const { cart, list, getYOULieklistAction, editCartAction } = props
  const [num, setNum] = useState()
  const [sum, setSum] = useState()
  const navigate = useNavigate()

  const checkAll = (ev) => {
    let list = cart.map(item => {
      item.type = ev.target.checked
      return item
    })
    editCartAction(list)
    getSum()
  }
  const getSum = useCallback(() => {
    let data = [...cart]
    let sum = 0;
    let num = 0
    data.filter(item => {
      if (item.type) {
        sum += item.price * item.num;
        num += item.num
      }
      return null

    })
    setNum(num)
    setSum(sum)
  }, [cart])

  const jiesuanFn = () => {
    const list = cart;
    let cartId = [];
    let cartList = [];
    list.forEach(item => {
      cartId.push(item.cartId);
      cartList.push(item)
    })
    perOrder({ cartId: cartId, totalMoney: sum }).then(res => {
      console.log('wwwwwww', res);
      if (res.data.code === 666) {
        navigate('/order', { state: { cartList, perOrderId: res.data.result.preOrderId, sum: sum } })
      }
    })

  }

  useEffect(() => {
    getYOULieklistAction()
    getSum()
  }, [getSum, getYOULieklistAction])
  return (
    <div>
      {
        cart.length === 0 ? <Carthead /> : <><Cartfoo cart={cart} getSum={getSum} /> <div className='cart-footer'>
          <div className='cart-radio'><input type="checkbox" checked={cart.length && cart.every(v => v.type)} onChange={ev => { checkAll(ev) }} /></div>
          <div className='checkall'>全选</div>
          <div className='cart-price'><span>共计</span><span className='han-price'>￥{sum}</span></div>


          <div className='handle' onClick={jiesuanFn} >去结算{num}</div>
        </div></>
      }
      <Maylike list={list}></Maylike>
    </div>
  )
}


export default connect(state => ({ cart: state.cart, list: state.rydata.list || [] }), { getYOULieklistAction, editCartAction })(Cart)